<?php
namespace app\common\model\food;

use Endroid\QrCode\QrCode as CodeMode;
use Endroid\QrCode\Writer\PngWriter;
use hema\alipay\Driver as Alipay;
use hema\wechat\Driver as Wechat;
use hema\Helper;
/**
 * 餐桌/包间模型
 */
class Table extends BaseModel
{
    // 定义表名
    protected $name = 'food_table';
    // 定义主键
    protected $pk = 'table_id';
    // 追加字段
    protected $append = ['qrcode'];
    
    /**
     * 获取餐桌码
     */
    public function getQrcodeAttr($value,$data)
    {
        $qrcode = [
            'h5' => '',
            'weixin' => '',
            'alipay' => '',
            'qrcode' => '',
        ];
        //生成存储路径
        if(!file_exists('./temp/food')){
            mkdir('./temp/food',0777,true);
        }
        //生成微信小程序码
        $wechat_path = '/temp/food/wechat-table-' . $data['table_id'] . '.png';
        if(!is_file('.' . $wechat_path)){
            $wx = new Wechat;
            if($wx->getUnlimitedQRCode($data['applet_id'],$wechat_path,'table-'.$data['shop_id'].'-'.$data['table_id'])){
                $qrcode['weixin'] = $wechat_path; 
            }
        }else{
            $qrcode['weixin'] = $wechat_path;  
        }
         //如果已经发布H5端代码
        if(is_file('./h5/food/index.html')){
            $h5_path = '/temp/food/h5-table-' . $data['table_id'] . '.png';
            if(!is_file('.' . $h5_path)){
                $writer = new PngWriter();
                $code = CodeMode::create(base_url() . 'h5/food/#/?applet_id=' . $data['applet_id'] . '&q=table-' . $data['shop_id'].'-'.$data['table_id'])->setSize(500);
                $result = $writer->write($code);
                $result->saveToFile('.' . $h5_path);
            } 
            $qrcode['h5'] = $h5_path;
        }
        //生成支付宝小程序码
        $alipay_path = '/temp/food/alipay-table-' . $data['shop_id'] . '.png';
        if(!is_file('.' . $alipay_path)){
            $alipay = new Alipay($data['applet_id']);
            if($alipay->openAppQrcodeCreate('table-'.$data['shop_id'].'-'.$data['table_id'],$alipay_path)){
                $qrcode['alipay'] = $alipay_path;
            }
        }else{
            $qrcode['alipay'] = $alipay_path;  
        } 
        //生成小程序聚合码
        $qrcode_path = '/temp/food/qrcode-table-' . $data['shop_id'] . '.png';
        if(!is_file('.' . $qrcode_path)){
            $writer = new PngWriter();
            $code = CodeMode::create(base_url() . 'food/' . $data['applet_id'] . '/table-'. $data['shop_id'].'-'.$data['table_id'])->setSize(500);
            $result = $writer->write($code);
            $result->saveToFile('.' . $qrcode_path);
        }
        $qrcode['qrcode'] = $qrcode_path;
        return $qrcode;
    }
    
    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }
    
    /**
     * 状态
     */
    public function getStatusAttr($value,$data)
    {
        $status = [10 => '空闲', 20 => '占用'];
        $order_id = [];//订单编号
        $pay_price = 0;//待付款
        $time = '';//开单时间
        $order = Order::where(['table_id'=>$data['table_id'],'order_status'=>10])->order('create_time','asc')->select();
        if(sizeof($order)){
            foreach ($order as $item){
                $order_id[] = $item['order_id']; 
                if($item['pay_status']['value'] != 20){
                   $pay_price = $pay_price + $item['pay_price'];
                }
            }
            $value = 20;
            $time = round((time() - strtotime($order[0]['create_time']))/60);
        }
        $start=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        return [
            'text' => $status[$value], 
            'value' => $value, 
            'order_id' => $order_id, 
            'time' => $time, //占用时间
            'pay_price' => Helper::number2($pay_price), //待收款
        ];
    }
    /**
     * 获取列表
     */
    public function getList($shop_id = 0, $status = 0, string $search = '')
    {
        //筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        !empty($search) && $filter['table_name'] = $search;
        // 执行查询
        $list = $this->with(['shop'])
            ->where($filter)
            ->order(['sort','table_id' => 'desc'])
            ->select();
        if($status > 0){
            $tablelist = $list;
            $list = [];
            for($n=0;$n<sizeof($tablelist);$n++){
                if($tablelist[$n]['status']['value'] == $status){
                    array_push($list,$tablelist[$n]);
                }
            }
        }
        return $list;
    }
    /**
     * 添加
     */
    public function add(array $data)
    {
        $data['applet_id'] = self::$applet_id;
        return $this->save($data);
    }
    
    
    /**
     * 编辑
     */
    public function edit(array $data)
    {
        return $this->save($data) !== false;
    }
    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete();
    }
}